package com.androidsocketd;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.androidsocketd.bean.Classes;
import com.androidsocketd.bean.ClassesBean;
import com.androidsocketd.bean.Post;
import com.androidsocketd.bean.PostBean;
import com.androidsocketd.bean.PostMessage;
import com.androidsocketd.bean.PostRebackMess;
import com.androidsocketd.bean.Product;
import com.androidsocketd.bean.ProductBean;
import com.androidsocketd.bean.ProductDetail;
import com.androidsocketd.bean.ProductDetailBean;
import com.androidsocketd.bean.Staff;
import com.androidsocketd.bean.StaffBean;
import com.androidsocketd.bean.Team;
import com.androidsocketd.bean.TeamBean;
import com.androidsocketd.dao.ClassesDao;
import com.androidsocketd.dao.PostDao;
import com.androidsocketd.dao.ProductDao;
import com.androidsocketd.dao.ProductDetailDao;
import com.androidsocketd.dao.StaffDao;
import com.androidsocketd.dao.TeamDao;
import com.androidsocketd.productdaobase.ProductDatabase;
import com.androidsocketd.util.AppExecutors;
import com.androidsocketd.util.ClonePostUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

// adb connect 127.0.0.1:7555

public class MainActivity extends AppCompatActivity {

    public Gson gson = new Gson();

    @BindView(R.id.showROOM)
    TextView showROOM;

    Handler mhandler = new Handler();

    ProductDao productDao;
    ProductDetailDao ProductDetailDao;
    ClassesDao classesDao;
    TeamDao teamDao;
    StaffDao staffDao;
    PostDao postDao;

    AppExecutors executors;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat formatter01 = new SimpleDateFormat("yyyyMMdd");


    private  int showId = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        productDao = ProductDatabase
                .getInstance(MainActivity.this)
                .getProductDao();

        ProductDetailDao = ProductDatabase
                .getInstance(MainActivity.this)
                .getProductDetailDao();
        classesDao = ProductDatabase
                .getInstance(MainActivity.this)
                .getClassesDao();
        teamDao = ProductDatabase
                .getInstance(MainActivity.this)
                .getTeamDao();
        staffDao = ProductDatabase
                .getInstance(MainActivity.this)
                .getStaffDao();

        postDao = ProductDatabase
                .getInstance(MainActivity.this)
                .getPostDao();

        executors = new AppExecutors();

        getMessage();
        getMessageDetail();
        getMessageClass();
        getMessageTeam();
        getMessageStaff();


    }

    StringBuffer stringBuffer = new StringBuffer();


    @OnClick(R.id.IntentMachine)
    public void IntentMachine(){
        Intent intent =new Intent();
        intent.setClass(MainActivity.this, MachineActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.getBase)
    public void getBaseRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {

                try {
                    List<Product> productList = productDao.getAllProducts();
                    if (productList.size() == 0) {
                        return;
                    }
                    for (Product product : productList) {
                        stringBuffer.append(product.toString() + "==");
                    }
                    showMess(stringBuffer.toString(), productList.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @OnClick(R.id.getMessageRoom)
    public void getMessageRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<ProductDetail> productDetailList = ProductDetailDao.getAllProductDetail();
                    ProductDetail productList = ProductDetailDao.getAllProductDetailOne("1");
                    if (productList == null || TextUtils.isEmpty(productList.getGridId())) {
                        return;
                    }
                    showMess(productList.toString(), 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @OnClick(R.id.getMessageClassRoom)
    public void getMessageClassRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Classes> classesList = classesDao.getAllClasses();
                    Classes classes = classesDao.getAllClassesByName("1");
                    if (classes == null || TextUtils.isEmpty(classes.getClassName())) {
                        return;
                    }
                    showMess(classes.toString(), 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @OnClick(R.id.getMessageClass)
    public void getMessageClass() {
        MessageClass();
    }

    private void MessageClass() {
        OkGo.<String>get("http://10.186.170.136:8036/class.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            ClassesBean classesBean = gson.fromJson(response.body(),
                                    new TypeToken<ClassesBean>() {
                                    }.getType());
                            if (classesBean.getCode() == 200) {
                                Toast.makeText(MainActivity.this, "size ===" + classesBean.getList().size(), Toast.LENGTH_SHORT).show();
                                final List<Classes> classesList = new ArrayList<Classes>();
                                classesList.clear();
                                if (classesBean.getList().size() > 0) {
                                    executors.getDiskIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                List<Classes> list = classesDao.getAllClasses();
                                                if (list.size() > 0) {
                                                    classesDao.delete(list);
                                                }
                                            } catch (Exception e) {
                                                Log.d("error==", e.toString());
                                            }
                                        }
                                    });
                                }

                                for (final ClassesBean.ListBean clessBean : classesBean.getList()) {
                                    final Classes classes = new Classes();
                                    classes.setClassId(clessBean.getClassId());
                                    classes.setClassName(clessBean.getClassName());
                                    classes.setMemo(clessBean.getMemo());
                                    classesList.add(classes);
                                }
                                executors.getDiskIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            classesDao.insert(classesList);
                                        } catch (Exception e) {
                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });

                            } else {

                            }
                        } catch (Exception e) {
                            Toast.makeText(MainActivity.this, "解析异常" + e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(MainActivity.this, "获取失败=" + response.body(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick(R.id.getMessageTeamRoom)
    public void getMessageTeamRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Team> teamList = teamDao.getAllTeam();
                    Team team = teamDao.getAllTeamByTeamId("1");
                    if (team == null || TextUtils.isEmpty(team.getTeamName())) {
                        return;
                    }
                    showMess(team.toString(), 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    @OnClick(R.id.getMessageTeam)
    public void getMessageTeam() {
        MessageTeam();
    }

    private void MessageTeam() {
        OkGo.<String>get("http://10.186.170.136:8036/team.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            TeamBean teamBean = gson.fromJson(response.body(),
                                    new TypeToken<TeamBean>() {
                                    }.getType());
                            if (teamBean.getCode() == 200) {
                                Toast.makeText(MainActivity.this, "size ===" + teamBean.getList().size(), Toast.LENGTH_SHORT).show();
                                final List<Team> teamList = new ArrayList<Team>();
                                teamList.clear();
                                if (teamBean.getList().size() > 0) {
                                    executors.getDiskIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                List<Team> list = teamDao.getAllTeam();
                                                if (list.size() > 0) {
                                                    teamDao.delete(list);
                                                }
                                            } catch (Exception e) {
                                                Log.d("error==", e.toString());
                                            }
                                        }
                                    });
                                }

                                for (final TeamBean.ListBean teamBeanOne : teamBean.getList()) {
                                    final Team team = new Team();
                                    team.setTeamId(teamBeanOne.getTeamId());
                                    team.setTeamName(teamBeanOne.getTeamName());
                                    team.setMemo(teamBeanOne.getMemo());
                                    teamList.add(team);
                                }
                                executors.getDiskIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            teamDao.insert(teamList);
                                        } catch (Exception e) {
                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });

                            } else {

                            }
                        } catch (Exception e) {
                            Toast.makeText(MainActivity.this, "解析异常" + e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(MainActivity.this, "获取失败=" + response.body(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick(R.id.getMessageStaffRoom)
    public void getMessageStaffRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Staff> teamList = staffDao.getAllStaff();
                    Staff team = staffDao.getAllStaffBystaffId("1");
                    if (team == null || TextUtils.isEmpty(team.getStaffName())) {
                        return;
                    }
                    showMess(team.toString(), 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    @OnClick(R.id.getMessageStaff)
    public void getMessageStaff() {
        MessageStaf();
    }

    private void MessageStaf() {
        OkGo.<String>get("http://10.186.170.136:8036/staff.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            StaffBean staffBean = gson.fromJson(response.body(),
                                    new TypeToken<StaffBean>() {
                                    }.getType());
                            if (staffBean.getCode() == 200) {
                                Toast.makeText(MainActivity.this, "size ===" + staffBean.getList().size(), Toast.LENGTH_SHORT).show();
                                final List<Staff> staffList = new ArrayList<Staff>();
                                staffList.clear();
                                if (staffBean.getList().size() > 0) {
                                    executors.getDiskIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                List<Staff> list = staffDao.getAllStaff();
                                                if (list.size() > 0) {
                                                    staffDao.delete(list);
                                                }
                                            } catch (Exception e) {
                                                Log.d("error==", e.toString());
                                            }
                                        }
                                    });
                                }

                                for (final StaffBean.ListBean teamListBean : staffBean.getList()) {
                                    final Staff staff = new Staff();
                                    staff.setStaffId(teamListBean.getStaffId());
                                    staff.setStaffName(teamListBean.getStaffName());
                                    staff.setMemo(teamListBean.getMemo());
                                    staffList.add(staff);
                                }
                                executors.getDiskIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            staffDao.insert(staffList);
                                        } catch (Exception e) {
                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });

                            } else {

                            }
                        } catch (Exception e) {
                            Toast.makeText(MainActivity.this, "解析异常" + e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(MainActivity.this, "获取失败=" + response.body(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick(R.id.getMessageDetail)
    public void getMessageDetail() {
        MessageProductDetal();
    }

    private void MessageProductDetal() {
        OkGo.<String>get("http://10.186.170.136:8036/productDetail.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            ProductDetailBean productDetailBean = gson.fromJson(response.body(),
                                    new TypeToken<ProductDetailBean>() {
                                    }.getType());
                            if (productDetailBean.getCode() == 200) {
                                Toast.makeText(MainActivity.this, "size ===" + productDetailBean.getList().size(), Toast.LENGTH_SHORT).show();
                                final List<ProductDetail> ProductDetailList = new ArrayList<ProductDetail>();
                                ProductDetailList.clear();
                                if (productDetailBean.getList().size() > 0) {
                                    executors.getDiskIO().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                List<ProductDetail> list = ProductDetailDao.getAllProductDetail();
                                                if (list.size() > 0) {
                                                    ProductDetailDao.delete(list);
                                                }
                                            } catch (Exception e) {
                                                Log.d("error==", e.toString());
                                            }
                                        }
                                    });
                                }

                                for (final ProductDetailBean.ListBean productDetail : productDetailBean.getList()) {
                                    final ProductDetail productDetail1 = new ProductDetail();

                                    productDetail1.setGridId(productDetail.getGridId());
                                    productDetail1.setGridInfoId(productDetail.getGridInfoId());
                                    productDetail1.setGridType(productDetail.getGridType());
                                    productDetail1.setPartsWeight(productDetail.getPartsWeight());
                                    productDetail1.setStandardWeight(productDetail.getStandardWeight());
                                    productDetail1.setStandardTolerance(productDetail.getStandardTolerance());
                                    productDetail1.setSmallWeight(productDetail.getSmallWeight());
                                    productDetail1.setSmallTolerance(productDetail.getStandardTolerance());
                                    productDetail1.setMemo(productDetail.getMemo());

                                    ProductDetailList.add(productDetail1);
                                }
                                executors.getDiskIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            ProductDetailDao.insert(ProductDetailList);
                                        } catch (Exception e) {
                                            Log.d("error==", e.toString());
                                        }

                                    }
                                });

                            } else {

                            }
                        } catch (Exception e) {
                            Toast.makeText(MainActivity.this, "解析异常" + e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(MainActivity.this, "获取数据出错=" + response.body(), Toast.LENGTH_SHORT).show();
                    }
                });
    }


    @OnClick(R.id.getMessage)
    public void getMessage() {

        MessageProduct();
    }

    private void MessageProduct() {
        OkGo.<String>get("http://10.186.170.136:8036/product.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ProductBean productBean = gson.fromJson(response.body(),
                                new TypeToken<ProductBean>() {
                                }.getType());
                        if (productBean.getCode() == 200) {
                            Toast.makeText(MainActivity.this, "size ===" + productBean.getList().size(), Toast.LENGTH_SHORT).show();
                            final List<Product> productList = new ArrayList<Product>();
                            productList.clear();
                            if (productBean.getList().size() > 0) {
                                executors.getDiskIO().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<Product> list = productDao.getAllProducts();
                                            if (list.size() > 0) {
                                                productDao.delete(list);
                                            }
                                        } catch (Exception e) {
                                            Log.d("error==", e.toString());
                                        }
                                    }
                                });
                            }

                            for (final ProductBean.ListBean product : productBean.getList()) {
                                final Product product1 = new Product();
                                product1.setGridId(product.getGridId());
                                product1.setGridCode(product.getGridCode());
                                product1.setGridName(product.getGridName());
                                product1.setMemo(product.getMemo());
                                productList.add(product1);
                            }
                            executors.getDiskIO().execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        productDao.insert(productList);
                                    } catch (Exception e) {
                                        Log.d("error==", e.toString());
                                    }

                                }
                            });

                        } else {

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(MainActivity.this, "获取失败=" + response.body(), Toast.LENGTH_SHORT).show();
                    }
                });
    }


    public void showMess(final String stringBuffer, final int size) {
        mhandler.post(new Runnable() {
            @Override
            public void run() {
                showROOM.setText(stringBuffer);
                Toast.makeText(MainActivity.this, stringBuffer + "productList==" + size, Toast.LENGTH_SHORT).show();
            }
        });

    }


    @OnClick(R.id.postMessageRoom)
    public void postMessageRoom() {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Post> teamList = postDao.getAllPost();
                    if (teamList.size() == 0 || TextUtils.isEmpty(teamList.get(0).getGridName())) {
                        return;
                    }
                    showMess(teamList.get(0).toString(), 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    @OnClick(R.id.postMessage)
    public void postMessage() {

        PostMessage postMessage = new PostMessage();

        long timeStr = System.currentTimeMillis();
        final Post post = new Post();

        post.setRecordId(formatter01.format(timeStr)+ RandomInt()+ (showId++));
        post.setWeighingTime(formatter.format(timeStr));
        post.setGridName("keda");
        post.setGridType("kedaType");
        post.setWeighingType("kedaWeight");
        post.setTotalWeight("96");
        post.setPartsWeight("10");
        post.setActualWeight("86");
        post.setQualifiedType("kedaQue");
        post.setClasses("kedaclass");
        post.setWorkTeam("kedaTeam");
        post.setStaff("kedaStaff");
        post.setMachineCode("kedaMAac");
        post.setInstrument("kedaIns");
        post.setMemo("kedaMEMO");


        postMessage.setDeviceCode("kedaDev");
        postMessage.setTime(formatter.format(System.currentTimeMillis()));

        List<PostBean> postList = new ArrayList<>();
        postList.clear();


        //clone 数据库实体转化为提交的实体
        PostBean postBean =new PostBean();
        ClonePostUtil.ClonePost(post,postBean);

        postList.add(postBean);
        postMessage.setList(postList);


        String postStr = gson.toJson(postMessage);

        Log.d("message===", postStr);

        OkGo.<String>get("http://10.186.170.136:8036/reback.json")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        PostRebackMess postRebackMess = gson.fromJson(response.body(),
                                new TypeToken<PostRebackMess>() {
                                }.getType());
                        if (postRebackMess.getCode() == 200) {
                            Toast.makeText(MainActivity.this, postRebackMess.getMessage(), Toast.LENGTH_SHORT).show();
                            post.setPostSuccess(1);
                            PoseInsert(post);
                        } else {
                            Toast.makeText(MainActivity.this, "上传失败" + postRebackMess.getMessage(), Toast.LENGTH_SHORT).show();
                            PoseInsert(post);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(MainActivity.this, "上传出错" , Toast.LENGTH_SHORT).show();
                        PoseInsert(post);
                    }
                });
    }

    private void PoseInsert(final Post post) {
        executors.getDiskIO().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    postDao.insert(post);
                } catch (Exception e) {
                    Log.d("error==", e.toString());
                }
            }
        });
    }

    private String RandomInt() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++)
        {
             result += random.nextInt(10);
        }
        return result;
    }
}
